//
//  TitleRepeatCell.m
//  MoneyIndividual
//
//  Created by Le Anh Tai on 1/15/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "TitleRepeatCell.h"

@implementation TitleRepeatCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.textFieldMode = TextFieldInputModeTableView;
        _tableView = [[TableView alloc] init];
        _tableView.delegate = self;
        _tableView.objects = @[REPEAT_NO,
                               REPEAT_DAILY,
                               REPEAT_WEEKLY,
                               REPEAT_EACH_2_WEEK,
                               REPEAT_MONTHLY];        
        [self.textField setInputView:_tableView];
        self.textField.clearButtonMode = UITextFieldViewModeNever;
    }
    
    return self;
}

- (void)setSelectedValue:(id)selectedValue
{
    [super setSelectedValue:selectedValue];
    
    if (selectedValue == nil)
    {
        self.textField.text = REPEAT_NO;
    }
    else if([selectedValue isKindOfClass:[NSManagedObject class]])
    {
        self.textField.text = [selectedValue getRepeatTypeString];
    }
}

#pragma mark - TextField delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    if (self.selectedValue)
    {
        _tableView.selectedObject = [self.selectedValue getRepeatTypeString];
    }
    else
    {
        _tableView.selectedObject = REPEAT_NO;
    }
    
}

#pragma mark - ExpenseIncomeTypeView delegate
- (void)table:(TableView *)view didSelectManageObject:(id )selectedObject
{
    NSNumber *type = [NSNumber numberWithInt:[selectedObject getRepeatTypeByRepeatTypeString:selectedObject]];
    if (self.selectedValue == nil)
    {
        NSManagedObject *transactionTemp = [[CoreData shared] newEntity:TRANSACTION_TEMP_ENTITY];
        [transactionTemp setValueEx:type forKey:TYPE_KEY];
        self.selectedValue = transactionTemp;
    }
    else
    {
        if (type.integerValue == RepeatTypeNone)
        {
            self.selectedValue = nil;
        }
        else
        {
            [self.selectedValue setValueEx:type forKey:TYPE_KEY];
            self.selectedValue = self.selectedValue;
        }        
    }
    
    [self.textField resignFirstResponder];
}

@end
